package com.alibaba.otter.canal.sample;
import java.net.InetSocketAddress;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.common.utils.AddressUtils;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.Message;
import com.alibaba.otter.canal.protocol.CanalEntry.Column;
import com.alibaba.otter.canal.protocol.CanalEntry.Entry;
import com.alibaba.otter.canal.protocol.CanalEntry.EntryType;
import com.alibaba.otter.canal.protocol.CanalEntry.EventType;
import com.alibaba.otter.canal.protocol.CanalEntry.RowChange;
import com.alibaba.otter.canal.protocol.CanalEntry.RowData;
import com.yupi.springbootinit.esdao.PostEsDao;
import com.yupi.springbootinit.model.dto.post.PostEsDTO;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
@SpringBootTest
public class SimpleCanalClientExample {
    @Resource
    private PostEsDao postEsDao;
@Test
    public  void main() {
        // 创建链接
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(AddressUtils.getHostIp(),
                11111), "example", "", "");
        int batchSize = 1000;
        int emptyCount = 0;
        try {
            connector.connect();
            connector.subscribe(".*\\..*");
            connector.rollback();
            int totalEmptyCount = 120;
            while (emptyCount < totalEmptyCount) {
                Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据
                long batchId = message.getId();
                int size = message.getEntries().size();
                if (batchId == -1 || size == 0) {
                    emptyCount++;
                    System.out.println("empty count : " + emptyCount);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                } else {
                    emptyCount = 0;
                    // System.out.printf("message[batchId=%s,size=%s] \n", batchId, size);
                    handleDATAChange(message.getEntries());
                }

                connector.ack(batchId); // 提交确认
                // connector.rollback(batchId); // 处理失败, 回滚数据
            }

            System.out.println("empty too many times, exit");
        } finally {
            connector.disconnect();
        }
    }
    private void handleDATAChange(List<CanalEntry.Entry> entrys) {
        for (CanalEntry.Entry entry : entrys) {
            //如果是事务头或者尾部则跳过
            if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
                continue;
            }
            //获取表名
            CanalEntry.RowChange rowChage = null;
            try {
                //反序列化
                rowChage = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {
                throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(),
                        e);
            }
            //获取操作类型
            CanalEntry.EventType eventType = rowChage.getEventType();
            System.out.println(String.format("================&gt; binlog[%s:%s] , name[%s,%s] , eventType : %s",
                    entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
                    entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
                    eventType));
            //获取行数据
            for (CanalEntry.RowData rowData : rowChage.getRowDatasList()) {
                //如果是删除操作
                if (eventType == CanalEntry.EventType.DELETE) {
                    //打印变化的数据
                    deleteFromEs(rowData.getBeforeColumnsList());
                    //如果是插入操作
                } else if (eventType == CanalEntry.EventType.INSERT) {
                    //打印变化的数据
                    insertToEs(rowData.getAfterColumnsList());
                    //如果是更新操作
                } else {
                    System.out.println("-------&gt; before");
                    deleteFromEs(rowData.getBeforeColumnsList());
                    System.out.println("-------&gt; after");
                    insertToEs(rowData.getAfterColumnsList());
                }
            }
        }
    }

    private void insertToEs(List<CanalEntry.Column> afterColumnsList) {
        PostEsDTO postEsDTO = new PostEsDTO();
        postEsDTO.setId(Long.valueOf(afterColumnsList.get(0).getValue()));
        postEsDTO.setTitle(afterColumnsList.get(1).getValue());


        postEsDTO.setContent(afterColumnsList.get(2).getValue());
        String tags = afterColumnsList.get(3).getValue();
        //将String数组转化为列表
        List<String> tagList = new ArrayList<>();
        for (String tag : tags.substring(1,tags.length()-1).split(",")) {
            tagList.add(tag.substring(1,tag.length()-1));
        }
        postEsDTO.setTags(tagList);
        postEsDTO.setThumbNum(Integer.valueOf(afterColumnsList.get(4).getValue()));
        postEsDTO.setFavourNum(Integer.valueOf(afterColumnsList.get(5).getValue()));
        postEsDTO.setUserId(Long.valueOf(afterColumnsList.get(6).getValue()));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            postEsDTO.setCreateTime(simpleDateFormat.parse(afterColumnsList.get(7).getValue()));
            postEsDTO.setUpdateTime(simpleDateFormat.parse(afterColumnsList.get(8).getValue()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        postEsDao.save(postEsDTO);


    }

    private void deleteFromEs(List<CanalEntry.Column> beforeColumnsList) {
        postEsDao.deleteById(Long.valueOf(beforeColumnsList.get(0).getValue()));
    }
    private void printEntry(List<Entry> entrys) {
        for (Entry entry : entrys) {
            if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND) {
                continue;
            }

            RowChange rowChage = null;
            try {
                rowChage = RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {
                throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(),
                        e);
            }

            EventType eventType = rowChage.getEventType();
            System.out.println(String.format("================&gt; binlog[%s:%s] , name[%s,%s] , eventType : %s",
                    entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
                    entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
                    eventType));

            for (RowData rowData : rowChage.getRowDatasList()) {
                if (eventType == EventType.DELETE) {
                    printColumn(rowData.getBeforeColumnsList());
                } else if (eventType == EventType.INSERT) {
                    printColumn(rowData.getAfterColumnsList());
                } else {
                    System.out.println("-------&gt; before");
                    printColumn(rowData.getBeforeColumnsList());
                    System.out.println("-------&gt; after");
                    printColumn(rowData.getAfterColumnsList());
                }
            }
        }
    }

    private static void printColumn(List<Column> columns) {
        for (Column column : columns) {
            System.out.println(column.getName() + " : " + column.getValue() + "    update=" + column.getUpdated());
        }
    }

}